#!/usr/bin/env python3
"""
改进的MCP服务器配置，防止重复应用问题
"""

import re
import uuid
from typing import Optional, Tuple
from sqlalchemy.orm import Session
from app.database import SessionLocal
from app.models import App, User


def normalize_app_name(app_name: str) -> str:
    """标准化应用名称，防止重复"""
    # 移除前后空格
    name = app_name.strip()
    
    # 统一大小写
    name = name.title()
    
    # 移除特殊字符，只保留字母、数字、空格和连字符
    name = re.sub(r'[^\w\s-]', '', name)
    
    # 合并多个空格为一个
    name = re.sub(r'\s+', ' ', name)
    
    return name


def get_or_create_app_safe(db: Session, user: User, app_id: str) -> App:
    """安全的获取或创建应用，防止重复"""
    # 标准化应用名称
    normalized_name = normalize_app_name(app_id)
    
    # 先尝试查找标准化后的名称
    app = db.query(App).filter(
        App.owner_id == user.id,
        App.name.ilike(normalized_name)
    ).first()
    
    if not app:
        # 如果标准化名称没找到，尝试精确匹配
        app = db.query(App).filter(
            App.owner_id == user.id,
            App.name == app_id
        ).first()
    
    if not app:
        # 创建新应用，使用标准化名称
        app = App(
            owner_id=user.id,
            name=normalized_name,
            is_active=True
        )
        db.add(app)
        db.commit()
        db.refresh(app)
    
    return app


def get_user_and_app_safe(db: Session, user_id: str, app_id: str) -> Tuple[User, App]:
    """安全的获取用户和应用"""
    from app.utils.db import get_or_create_user
    
    user = get_or_create_user(db, user_id)
    app = get_or_create_app_safe(db, user, app_id)
    return user, app


def migrate_existing_apps(user_id: str):
    """迁移现有重复应用到标准化名称"""
    db = SessionLocal()
    try:
        from app.models import User
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            print(f"用户 {user_id} 不存在")
            return
        
        # 查找所有应用
        apps = db.query(App).filter(App.owner_id == user.id).all()
        
        # 按标准化名称分组
        name_groups = {}
        for app in apps:
            normalized = normalize_app_name(app.name)
            if normalized not in name_groups:
                name_groups[normalized] = []
            name_groups[normalized].append(app)
        
        # 处理重复应用
        for normalized_name, app_list in name_groups.items():
            if len(app_list) > 1:
                print(f"发现重复应用 '{normalized_name}': {len(app_list)} 个")
                
                # 保留第一个应用
                keep_app = app_list[0]
                
                # 更新保留应用的名称
                if keep_app.name != normalized_name:
                    keep_app.name = normalized_name
                    db.commit()
                
                # 合并其他应用到保留的应用
                for merge_app in app_list[1:]:
                    # 更新Memory表
                    memories = db.query(App.models.Memory).filter(
                        App.models.Memory.app_id == merge_app.id
                    ).all()
                    for memory in memories:
                        memory.app_id = keep_app.id
                    
                    # 更新MemoryAccessLog表
                    logs = db.query(App.models.MemoryAccessLog).filter(
                        App.models.MemoryAccessLog.app_id == merge_app.id
                    ).all()
                    for log in logs:
                        log.app_id = keep_app.id
                    
                    # 删除合并的应用
                    db.delete(merge_app)
                    print(f"已合并应用 {merge_app.id} 到 {keep_app.id}")
        
        db.commit()
        print("迁移完成")
        
    except Exception as e:
        db.rollback()
        print(f"迁移出错: {e}")
    finally:
        db.close()


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print("用法: python mcp_config_fix.py <user_id>")
        sys.exit(1)
    
    user_id = sys.argv[1]
    migrate_existing_apps(user_id)